package com.yswy.common.utils.http;

import com.alibaba.fastjson.JSONObject;
import com.yswy.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.security.cert.X509Certificate;
import java.util.Map;

/**
 * 通用http发送方法
 * 
 * @author ruoyi
 */
public class HttpUtils
{
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url)
    {
        return sendGet(url, StringUtils.EMPTY);
    }

    public static String sendGetToFromdate(String url , Map<String, Object> params) throws Exception{


        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "------------------------------0ea3fcae38ff", Charset.defaultCharset());
        multipartEntity.addPart("skey", new StringBody("哈哈哈哈哈", Charset.forName("UTF-8")));
        multipartEntity.addPart("operator", new StringBody("啦啦啦啦", Charset.forName("UTF-8")));
        multipartEntity.addPart("VrfKey", new StringBody("渣渣渣", Charset.forName("UTF-8")));
        multipartEntity.addPart("StatCode", new StringBody("00", Charset.forName("UTF-8")));
        multipartEntity.addPart("mass_id", new StringBody("1234", Charset.forName("UTF-8")));
        multipartEntity.addPart("reference_id", new StringBody("21231544", Charset.forName("UTF-8")));

        HttpPost request = new HttpPost(url);
        request.setEntity(multipartEntity);
        request.addHeader("Content-Type", "Content-Disposition: form-data; boundary=------------------------------0ea3fcae38ff");

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(request);

        InputStream is = response.getEntity().getContent();
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = in.readLine()) != null)
        {
            buffer.append(line);
        }
        is.close();
        in.close();
        return  buffer.toString() ;
    }

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param)
    {
        return sendGet(url, param, "UTF-8");
    }



    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @param contentType 编码类型
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param, String contentType)
    {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try
        {
            String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();

            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "form-data");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            log.info("recv - {}", result);
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {
                if (in != null)
                {
                    in.close();
                }
            }
            catch (Exception ex)
            {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param)
    {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try
        {
            String urlNameString = url;
            log.info("sendPost - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            log.info("recv - {}", result);
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            }
            catch (IOException ex)
            {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

    public static String sendSSLPost(String url, String param)
    {
        StringBuilder result = new StringBuilder();
        String urlNameString = url + "?" + param;
        try
        {
            log.info("sendSSLPost - {}", urlNameString);
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
            URL console = new URL(urlNameString);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String ret = "";
            while ((ret = br.readLine()) != null)
            {
                if (ret != null && !"".equals(ret.trim()))
                {
                    result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
                }
            }
            log.info("recv - {}", result);
            conn.disconnect();
            br.close();
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
        }
        return result.toString();
    }




    public static String post(String actionUrl, Map<String, Object> params) throws IOException {

        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--";
        String LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";
        URL uri = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        conn.setReadTimeout(30 * 1000); // 缓存的最长时间
        conn.setDoInput(true);// 允许输入
        conn.setDoOutput(true);// 允许输出
        conn.setUseCaches(false); // 不允许使用缓存
        conn.setRequestMethod("POST");
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
        StringBuilder sb = new StringBuilder();
        if (params!=null) {
            // 首先组拼文本类型的参数
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINEND);
                sb.append("Content-Disposition: form-data; name=\""
                        + entry.getKey() + "\"" + LINEND);
                sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
                sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
                sb.append(LINEND);
                sb.append(entry.getValue());
                sb.append(LINEND);
            }
        }

        DataOutputStream outStream = new DataOutputStream(
                conn.getOutputStream());
        if (!TextUtils.isEmpty(sb.toString())) {
            outStream.write(sb.toString().getBytes());
        }
        // 请求结束标志
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();

        // 得到响应码
        int res = conn.getResponseCode();
        InputStream in = conn.getInputStream();
        if (res == 200) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = bufferedReader.readLine()) != null){
                buffer.append(line);
            }

//          int ch;
//          StringBuilder sb2 = new StringBuilder();
//          while ((ch = in.read()) != -1) {
//              sb2.append((char) ch);
//          }
            return buffer.toString();
        }
        outStream.close();
        conn.disconnect();
        return in.toString();
    }

    public static String sendHttpPost(String url, String body) throws Exception {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        httpPost.addHeader("Content-Type", "application/json");

        //httpPost.setHeader("Content-Type","application/json;charset=utf-8");
        StringEntity postingString = new StringEntity(body,
                "utf-8");
        httpPost.setEntity(postingString);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        //System.out.println(response.getStatusLine().getStatusCode() + "\n");
        HttpEntity entity = response.getEntity();
        String responseContent = EntityUtils.toString(entity, "UTF-8");
        log.info(responseContent);

        response.close();
        httpClient.close();
        return responseContent;
    }

    public static String sendHttpPostByToken(String url, String body , String token) throws Exception {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        httpPost.addHeader("Content-Type", "application/json");
        httpPost.addHeader("Authorization", token);
        //httpPost.setHeader("Content-Type","application/json;charset=utf-8");
        StringEntity postingString = new StringEntity(body,
                "utf-8");
        httpPost.setEntity(postingString);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        //System.out.println(response.getStatusLine().getStatusCode() + "\n");
        HttpEntity entity = response.getEntity();
        String responseContent = EntityUtils.toString(entity, "UTF-8");
        log.info(responseContent);

        response.close();
        httpClient.close();
        return responseContent;
    }


//    public static void main(String[] args) {
//        //测试公司的API接口，将json当做一个字符串传入httppost的请求体
//        String result = null;
//        HttpClient client = HttpClients.createDefault();
//        URIBuilder builder = new URIBuilder();
//        URI uri = null;
//        try {
//            uri = builder.setScheme("http")
//                    .setHost("120.46.147.54:9002")
//                    .setPath("/payment/alipay/generateOrder")
//                    .build();
//
//            HttpPost post = new HttpPost(uri);
//            //设置请求头
//            post.setHeader("Content-Type", "application/json");
//            String body = "{" +
//                    "\"amount\": \"10\"," +
//                    "\"appid\": \"2021002191682896\"," +
//                    "\"callbackUrl\": \"http://120.46.147.54:9111/app/pay/callbackPayOrder\"," +
//                    "\"itemsInfo\": \"1\"," +
//                    "\"privatekey\": \"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCc8rwrADJp2h/h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K7c4mhUdFrCxnoQ5vz/9lB4aPa9+7eOokaV7Hxh85JSS1Sp9dyx+rJnvin0KKIjAFMSt4JFhjb/Etnw4J4LFvB87SazRYRTSeg/hrhZHPtv87LNO8WBQCppGZN41uAQSeqYRBAoGBAK4x2+p8umxFq7RxeH4gZCE4Z+T1seysnhkMFInSHOvaL3MPstSc95MyuqffBvO5ItF+S7ibq4vBrei2K7qHPBJr20tDbsswzkmh5SJhtLQ86wATZDGfLJspE4wviDfZYmPnSnGyQfPFcxmIhzbZGDpNi0Ls/HysAxzFZOOz1LKVAoGADUvZyi7K4xF3Z8VbIHH1Wtse4u4vyOf14L+YXiYvkak5Nz7/u9uun8Jr3Rx0gcZuOOy7crCQtCHEfZPbJ/iw9Rel0dZYalHm/sraFU/ELTsUqiTtaTrUkV/gbn6mmtki7Wk88vD+FdtfPeAfnCh6wcFIF1topA5P3w1NCo0aaeA=\"," +
//                    "\"productid\": \"0\"," +
//                    "\"publickey\": \"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj3sBTKaKfi7NPnuHLJclem+CqXivZe2gLlZjSEwfkoNxqNMUHt+VSWuK2twbew7k8OCAxkO5/Tlrv1xzDgmyKvkHJRvZAJa0GQbPMOdVmCzvOtMus5sFp+VzRjhyJ2JRI0k9VWoW1qRRkquGSgURfflESGA85+kpiTuT8ohtPadcmgu1HsEHuSMSfBDowccJ6nl4hRFVuMtMuw3QLolFT0p6kZjN2p3J/YwXT52BHGaOp7zedT+/FwXVTRYz+W34qJlZKCt09oTED2ZWEFWBIuKLpJ6GirdXWXbx1MYNDj2StJd6mDeTLJsVWpLq9qIveGIHy4Ng46Kww74/vG+hawIDAQAB\"," +
//                    "\"subject\": \"1\"," +
//                    "\"uid\": \"718ef714f87e4412a8d8c2932a207d92\"" +
//                    "}";
//            //设置请求体
//            post.setEntity(new StringEntity(body));
//            //获取返回信息
//            HttpResponse response = client.execute(post);
//            result = response.toString();
//        } catch (Exception e) {
//            System.out.println("接口请求失败"+e.getStackTrace());
//        }
//        System.out.println("接口请求"+ result);
//    }


    private static class TrustAnyTrustManager implements X509TrustManager
    {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
        {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)
        {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers()
        {
            return new X509Certificate[] {};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier
    {
        @Override
        public boolean verify(String hostname, SSLSession session)
        {
            return true;
        }
    }
}